import { getMedifoodClassifications } from '../../Service/ClassificationService';
import { addMedifoodInfo } from '../../Service/CategoryService';
import { uploadFileBySDK } from '../../Service/uploadService';

Page({
  data: {
    selectedOperatorIndex: null,
    operatorOptions: [],
    showPicker: false,
    otherTitles: [
      { titleName: '适应症', sureName: 'indication' },
      { titleName: '配方', sureName: 'Medifood_recipe' },
      { titleName: '用法', sureName: 'Medifood_usage' },
      { titleName: '治疗疾病', sureName: 'treated_disease' },
      { titleName: '药膳香味', sureName: 'Medifood_aroma' },
      { titleName: '药膳颜色', sureName: 'Medifood_color' },
      { titleName: '药膳味道', sureName: 'Medifood_flavor' },
      { titleName: '关联症状', sureName: 'Associated_symptoms' },
      { titleName: '食用方法', sureName: 'Edible_method' },
      { titleName: '治疗部位', sureName: 'treatment_site' }
    ],
    imageSrc: [], // 存储上传的图片URL
    medicineName: '', // 新增药膳名称字段
    caseDetail: {}
  },

  async onLoad() {
    try {
      const mediclassify = await getMedifoodClassifications();
      const operatorOptions = mediclassify.map(item => ({
        name: item.name,
        id: item.id,
      }));
      this.setData({ operatorOptions: operatorOptions });
    } catch (error) {
      console.error('加载药膳分类信息失败:', error);
    }
  },

  togglePicker() {
    this.setData({ showPicker: !this.data.showPicker });
  },

  selectOption(e) {
    const selectedIndex = e.currentTarget.dataset.index;
    const selectedClassificationId = this.data.operatorOptions[selectedIndex].id;
    this.setData({
      selectedOperatorIndex: selectedIndex,
      showPicker: false,
      'caseDetail.classification_id': selectedClassificationId, // 更新药膳信息中的分类id
    });
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        console.log('tempFilePath', tempFilePath);
        if (this.beforeUpload(tempFilePath)) {
          try {
            const data = await uploadFileBySDK(tempFilePath, '药膳图片');
            console.log('data.path', data.path);
            this.setData({
              imageSrc: this.data.imageSrc.concat(data.path)
            });
            wx.showToast({
              title: '图片上传成功',
              icon: 'success'
            });
          } catch (error) {
            console.error("图片上传失败", error);
            wx.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        }
      },
      fail: (err) => {
        console.error("选择图片失败", err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  //检查图片的格式是否符合要求
  beforeUpload(filePath) {
    //以“.”来区分文件名或扩展名 截取字符串
    const fileType = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
    const isJpgOrPng = fileType === 'jpg' || fileType === 'jpeg' || fileType === 'png';
    if (!isJpgOrPng) {
      wx.showToast({
        title: '图片格式要求为 JPG 或 PNG!',
        icon: 'none'
      });
      return false;
    }
    return true;
  },

  viewImage() {
    wx.previewImage({
      urls: this.data.imageSrc
    });
  },

  validateForm() {
    if (!this.data.medicineName) {
      wx.showToast({
        title: '请填写药膳名称!',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    if (this.data.selectedOperatorIndex === null) {
      wx.showToast({
        title: '请选择分类!',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    return true;
  },

  onMedicineNameInput(e) {
    this.setData({
      medicineName: e.detail.value
    });
  },

  onOtherInfoInput(e) {
    const fieldName = e.currentTarget.dataset.field;
    const fieldValue = e.detail.value;
    const update = {};
    update[`caseDetail.${fieldName}`] = fieldValue;
   
    // 更新数据
    this.setData(update); 

    // console.log('更新后的 caseDetail:', this.data.caseDetail);
  },

  async publish() {
    if (!this.validateForm()) {
      return;
    }

    // 检查 imageSrc 数组中是否有图片 URL，直接使用已上传的图片 URL
    const imageUrl = this.data.imageSrc.length > 0 ? this.data.imageSrc[0] : '';

    const medifoodData = {
      classification_id: this.data.caseDetail.classification_id,
      name: this.data.medicineName,
      thumbs: this.data.imageSrc.join(','), // 将图片URL合并成字符串
      ...this.data.caseDetail // 包括其他信息
    };
    console.log(' medifoodData.thumbs', medifoodData.thumbs);

    try {
      const newMedifoodId = await addMedifoodInfo(medifoodData);
      console.log('新增药膳信息', newMedifoodId);
      wx.showToast({
        title: '发布成功！',
        icon: 'success',
        duration: 2000
      });
      this.setData({
        selectedOperatorIndex: null,
        imageSrc: [],
        medicineName: '',
        caseDetail: {}
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    } catch (error) {
      wx.showToast({
        title: '发布失败！',
        icon: 'none',
        duration: 2000
      });
      console.error('发布失败', error);
    }
  }
});
